package com.szf.system.web;

import javax.servlet.http.HttpSession;

import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import com.szf.account.entity.Account;
import com.szf.account.service.AccountService;
import com.szf.base.bean.SinlogConstants;
import com.szf.base.exception.GenericException;
import com.szf.base.web.BaseActionSupport;
import com.szf.base.web.Principle;
import com.szf.util.MD5Util;

@Namespace("/")
@Results({
		@Result(name = "success", type = "redirectAction", location = "main.action"),
		@Result(name = "error", location = "/login.jsp") })
public class LoginAction extends BaseActionSupport {
	@Autowired
	private AccountService accountService;

	private String errMsg;

	private Account account;

	@Override
	public String execute() {
		try {
			Account confAccount = accountService.findByName(account
					.getUserName());
			auth(confAccount);

			HttpSession session = request.getSession();
			Principle principle = new Principle();
			principle.setAccountId(confAccount.getAccountId());
			principle.setUserName(confAccount.getUserName());
			principle.setIsAdmin(confAccount.getAccountType());
			session.setAttribute(SinlogConstants.PRINCIPLE_KEY, principle);

			return super.execute();

		} catch (GenericException e) {
			request.setAttribute("errMsg", e.getMessage());
			return "error";
		}

	}

	public void auth(Account confAccount) {
		if (confAccount == null) {
			throw new GenericException("account null");
		}
		String encMD5 = MD5Util.getStringMD5(account.getPassword());
		if (!confAccount.getPassword().equals(encMD5)) {
			throw new GenericException("error password");
		}
	}

	public Account getAccount() {
		return account;
	}

	public void setAccount(Account account) {
		this.account = account;
	}

	public String getErrMsg() {
		return errMsg;
	}

	public void setErrMsg(String errMsg) {
		this.errMsg = errMsg;
	}

}
